use warnings;
use strict;

sub TMDb {
	my ($title, $tt, $tmdb_id, $edit, $re, $xbmc) = @_ ;
	my $api = '963842d796d7b1c0c5b941e92eca5121';
	my $record = '';
	my $count = 0;
	my $image_url;
	
	# check for existing record
	open (RDB, "<$VAR{'DataDir'}/ppweb_tmdb.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/ppweb_tmdb.txt, $! (TM01)", 1, 0);
	while (<RDB>){
		# tt match
		if ($tt and m!^(\d+)$tt [^\t]+\t(.+)!){
			$tmdb_id = $1;
			$record = "$2\n";
			&Print ("TMDb cached record found (IMDb id match) for: $title (TM01)", 4, 0);
			last;
		}
		# tmdb id match
		elsif ($tmdb_id and m!^$tmdb_id(tt\d+)? [^\t]+\t(.+)!){
			if ($1){ $tt = $1; }
			$record = "$2\n";
			&Print ("TMDb cached record found (TMDb id match) for: $title (TM01)", 4, 0);
			last;
		}
		# title match
		elsif ($title and m!^(\d+)(tt\d+)? $title\t(.+)!){
		#elsif ($title and m!^(\d+)(tt\d+)? $title(?:[^\t]+)?\t(.+)!){
			$tmdb_id = $1;
			if ($2){ $tt = $2; }
			$record = "$3\n";
			&Print ("TMDb cached record found (title match) for: $title (TM01)", 4, 0);
			last;
		}
	}
	close RDB or warn $!;
	
	# get new or updated record
	if (!$record or $edit eq 'up'){
		#&Print ("Fetching TMDb record: $title (TM02)", 5, 0);
		require LWP::UserAgent;
		my $user_agent = LWP::UserAgent->new;
		$user_agent->agent("Mozilla/8.1");
		my $url;
		# get tmdb id
		unless ($tmdb_id){
			# title search
			unless ($tt){ 
				$tt = $title; 
				$tt =~ s! !+!g; # using tt so no perm mod of $title
				$url = "http://api.themoviedb.org/2.1/Movie.search/en/xml/$api/$tt";
				# http://api.themoviedb.org/3/search/movie?api_key=$api&query=$tt
				$tt = '';
			}
			# tt search
			else { $url = "http://api.themoviedb.org/2.1/Movie.imdbLookup/en/xml/$api/$tt"; }
			my $response = $user_agent->get($url);
			if ($response->is_success and $response->decoded_content) {
				$record = $response->decoded_content;
				my @xml = split (/[\r\n]+/, $record);
				($record, $count, $tmdb_id, $image_url, $tt) = &ParseTMDb (\@xml, $api, $title, $re, $tmdb_id, $tt, '', '');
				if ($tmdb_id){
					&Print ('TMDb id fech successful: '.$tmdb_id.' (TM04)', 5, 0);
				}
			}
			else { &Print ('TMDb id fetch failed: '.$response->status_line.' (TM04)', 1, 0); }
		}
		# get tmdb record
		if ($tmdb_id and $count <= 1){ # 0 or 1
			# http://api.themoviedb.org/3/movie/$tt?api_key=$api
			$url = "http://api.themoviedb.org/2.1/Movie.getInfo/en/xml/$api/$tmdb_id";
			# # http://api.themoviedb.org/3/movie/$tmdb_id?api_key=$api
			my $response = $user_agent->get($url);
			if ($response->is_success and $response->content) {
				$record = $response->decoded_content;
				my @xml = split (/[\r\n]+/, $record);
				($record, $count, $tmdb_id, $image_url, $tt) = &ParseTMDb (\@xml, $api, $title, $re, $tmdb_id, $tt, $user_agent, $edit);
				# fetch image, if we don't have one
				my $image = $tt;
				unless ($tt){ $image = $tmdb_id } # use ttnum if possible
				if ($image_url and !-e "$VAR{'PPWebDir'}/images/$image.jpg"){
					$response = $user_agent->get($image_url, ':content_file' => "$VAR{'PPWebDir'}/images/$image.jpg");
					unless ($response->is_success) {
						&Print ('TMDb image fetch failed: '.$response->status_line.' (TM05)', 1, 0);
					}
					&Print ('TMDb image fetch successful: '.$image.'.jpg (TM05)', 4, 0);
				}
				elsif (-e "$VAR{'PPWebDir'}/images/$image.jpg"){
					&Print ('Using cached image for TMDb record (TM05)', 4, 0);
				}	
				# print record
				if ($record){
					if ($record eq 'No listing found at The Movie Database'){
						&Print ('TMDb record not found for: '.$title.' (TM05)', 3, 0)
					}
					else {
						&Print ('TMDb record fetch successful for: '.$title.' (TM05)', 4, 0);
						if ($edit eq 'up'){
							local ($^I, @ARGV) = ('.bak', "$VAR{'DataDir'}/ppweb_tmdb.txt");
							while(<>){
								if ($. == 1) { 
									print $record; # new and updated records
									unless (m!^$tmdb_id!){ print; } # replaced record on 1st line
								}
								elsif (m!^$tmdb_id!){ next; } # replaced record elsewhere
								else { print; }
							}
						}
						else {
							open (WDB, ">>$VAR{'DataDir'}/ppweb_tmdb.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/ppweb_tmdb.txt, $! (TM06)", 1, 0);
								print WDB $record;
							close WDB or warn $!;
						}
						$record =~ s!^[^\t]+\t!!; # remove leading id and title
						if ($edit eq 'up'){ $record = "Record Updated\n\n$record"; }
					}
				}
				else {
					&Print ("TMDb record is empty, writing TMDb response to $VAR{'DataDir'}/response_tmdb.txt (TM06)", 1, 0);
					open (WDB, ">$VAR{'DataDir'}/response_tmdb.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/response_tmdb.txt, $! (TM06)", 1, 0);
						print WDB $response->headers_as_string;
						print WDB $response->decoded_content;
					close WDB or warn $!;
				}
			}
			else { &Print ('TMDb record fetch failed: '.$response->status_line.' (TM06)', 1, 0); }
		}
	}
	
	# delete image
	if ($edit eq 'img'){
		if (-e "$VAR{'PPWebDir'}/images/$tt.jpg"){ 
			&Delete ("$VAR{'PPWebDir'}/images", "$tt.jpg", 'LI07');
		}
	}
	# delete record
	if ($edit eq 'del'){
		&Print ("Deleting TMDb record: $title (TM07)", 4, 0);
		local ($^I, @ARGV) = ('.bak', "$VAR{'DataDir'}/ppweb_tmdb.txt");
		while(<>){
			if (m!^$tmdb_id!){ next; } # edit del
			else { print; }
		}
# 		if (-e "$VAR{'PPWebDir'}/images/$tt.jpg"){ &Delete ("$VAR{'PPWebDir'}/images", "$tt.jpg", 'TM08'); }
# 		elsif  (-e "$VAR{'PPWebDir'}/images/$tmdb_id.jpg"){ &Delete ("$VAR{'PPWebDir'}/images", "$tmdb_id.jpg", 'TM09'); }
		$record = "<pre><font face=\"Monospace,Courier,Courier New\">Record Deleted</font></pre></td></tr><tr><td>";
	}		
	# process record for xbmc nfo
	elsif ($record and $xbmc){
		$record =~ s!:([^:]+):(\d+)!<A HREF="http://www.themoviedb.org/person/$2">$1</A>!g;
		$record =~ s!<br>\t(\w{3} \d{2} \d{4})$!Record:&nbsp;<a href=\"$VAR{'DbCgi'}?do=tmdb&amp;tt=$tt&amp;nt=$title&amp;id=$tmdb_id&amp;db=up&amp;re=$re\">update</a>&nbsp;<a href=\"$VAR{'DbCgi'}?do=tmdb&amp;tt=$tt&amp;nt=$title&amp;id=$tmdb_id&amp;db=del&amp;re=$re\">delete</a>&nbsp;Image:&nbsp;<a href=\"$VAR{'DbCgi'}?do=tmdb&amp;tt=$tt&amp;nt=$title&amp;id=$tmdb_id&amp;db=img&amp;re=$re\">delete</a>\n\n$1\n!;
		$record =~ s!<br>\t?!\n!g;
		if ($count > 1){
			#$record =~ s!^[^\t]+\t!!; # lead on first record
			#$record =~ s!\n[^\t]+\t!\n\n!g; # lead on other records
			#$record =~ s!<br>\t?!\n!g; # is earlier OK?
			$record =~ s!(Record[^\n]+\n\n)?\w{3} \d{2} \d{4}!!g;# last listing will have Record
			$record =~ s!(\d+)[^\n]+\tTitle.....: ([^\n]+)!Title.....: [<a href=\"$VAR{'DbCgi'}?do=tmdb&amp;tt=&amp;nt=$title&amp;id=$1&amp;db=&amp;re=$re\">$2</a>]!g;
			$record = "Multiple matches found, please select one of the following titles:\n\n$record";
			$record = "<pre><font face=\"Monospace,Courier,Courier New\">\n$record</font></pre></td></tr><tr><td>";
		}
		elsif (-e "$VAR{'PPWebDir'}/images/$tt.jpg"){
			$record = "<img SRC=\"$VAR{'PPWebUrl'}/images/$tt.jpg\" style=\"float:right\; padding-right:50px;\">
			<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre><br clear=\"all\"></td></tr><tr><td>";
		}
		elsif (-e "$VAR{'PPWebDir'}/images/$tmdb_id.jpg"){
			if ($tt){ # temporary to update my db images
				&Save ("$VAR{'PPWebDir'}/images", $tmdb_id, 'jpg', "$VAR{'PPWebDir'}/images", $tt, 'jpg', 'TM10');
				$record = "<img SRC=\"$VAR{'PPWebUrl'}/images/$tt.jpg\" style=\"float:right\; padding-right:50px;\">
				<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre><br clear=\"all\"></td></tr><tr><td>";
			}
			else {
				$record = "<img SRC=\"$VAR{'PPWebUrl'}/images/$tmdb_id.jpg\" style=\"float:right\; padding-right:50px;\">
				<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre><br clear=\"all\"></td></tr><tr><td>";
			}
		}
		else { $record = "<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre><br clear=\"all\"></td></tr><tr><td>"; }
	}
	# process record
	elsif ($record){
		$record =~ s!:([^:]+):(\d+)!<A HREF="http://www.themoviedb.org/person/$2">$1</A>!g;
		$record =~ s!<br>\t(\w{3} \d{2} \d{4})$!Record:&nbsp;<a href=\"$VAR{'DbCgi'}?do=tmdb&amp;tt=$tt&amp;nt=$title&amp;id=$tmdb_id&amp;db=up&amp;re=$re\">update</a>&nbsp;<a href=\"$VAR{'DbCgi'}?do=tmdb&amp;tt=$tt&amp;nt=$title&amp;id=$tmdb_id&amp;db=del&amp;re=$re\">delete</a>&nbsp;Image:&nbsp;<a href=\"$VAR{'DbCgi'}?do=tmdb&amp;tt=$tt&amp;nt=$title&amp;id=$tmdb_id&amp;db=img&amp;re=$re\">delete</a>\n\n$1\n!;
		$record =~ s!<br>\t?!\n!g;
		if ($count > 1){
			#$record =~ s!^[^\t]+\t!!; # lead on first record
			#$record =~ s!\n[^\t]+\t!\n\n!g; # lead on other records
			#$record =~ s!<br>\t?!\n!g; # is earlier OK?
			$record =~ s!(Record[^\n]+\n\n)?\w{3} \d{2} \d{4}!!g;# last listing will have Record
			$record =~ s!(\d+)[^\n]+\tTitle.....: ([^\n]+)!Title.....: [<a href=\"$VAR{'DbCgi'}?do=tmdb&amp;tt=&amp;nt=$title&amp;id=$1&amp;db=&amp;re=$re\">$2</a>]!g;
			$record = "Multiple matches found, please select one of the following titles:\n\n$record";
			$record = "<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre></td></tr><tr><td>";
		}
		elsif (-e "$VAR{'PPWebDir'}/images/$tt.jpg"){
			$record = "<img SRC=\"$VAR{'PPWebUrl'}/images/$tt.jpg\" style=\"float:right\; padding-right:50px;\">
			<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre><br clear=\"all\"></td></tr><tr><td>";
		}
		elsif (-e "$VAR{'PPWebDir'}/images/$tmdb_id.jpg"){
			if ($tt){ # temporary to update my db images
				&Save ("$VAR{'PPWebDir'}/images", $tmdb_id, 'jpg', "$VAR{'PPWebDir'}/images", $tt, 'jpg', 'TM10');
				$record = "<img SRC=\"$VAR{'PPWebUrl'}/images/$tt.jpg\" style=\"float:right\; padding-right:50px;\">
				<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre><br clear=\"all\"></td></tr><tr><td>";
			}
			else {
				$record = "<img SRC=\"$VAR{'PPWebUrl'}/images/$tmdb_id.jpg\" style=\"float:right\; padding-right:50px;\">
				<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre><br clear=\"all\"></td></tr><tr><td>";
			}
		}
		else { $record = "<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre><br clear=\"all\"></td></tr><tr><td>"; }
	}
	else { $record = "<pre><font face=\"Monospace,Courier,Courier New\">Unable to fetch record</font></pre></td></tr><tr><td>";}
	return $record;
# tmdb api key 963842d796d7b1c0c5b941e92eca5121
# http://api.themoviedb.org/3/configuration
# To build an image URL, you will need 3 pieces of data. The base_url, size and file_path. 
# Simply combine them all and you will have a fully qualified URL. Here's an example URL:
# http://cf2.imgobject.com/t/p/w500/mOTtuakUTb1qY6jG6lzMfjdhLwc.jpg
# i want w342. Options are "w92", w154", "w185", "w342", "w500",
# http://cf2.imgobject.com/t/p/w342/c2SQMd00CCGTiDxGXVqA2J9lmzF.jpg

# http://api.themoviedb.org/3/search/movie?api_key=963842d796d7b1c0c5b941e92eca5121&query=War+Horse+2011
# http://api.themoviedb.org/3/search/movie?api_key=963842d796d7b1c0c5b941e92eca5121&query=Rambo
# http://api.themoviedb.org/3/movie/57212?api_key=963842d796d7b1c0c5b941e92eca5121
# http://api.themoviedb.org/3/movie/57212/casts?api_key=963842d796d7b1c0c5b941e92eca5121
# http://api.themoviedb.org/3/movie/tt1606378?api_key=963842d796d7b1c0c5b941e92eca5121
# &append_to_response=releases,trailers,alternative_titles,casts,
# &language=en

# http://api.themoviedb.org/2.1/Movie.imdbLookup/en/xml/963842d796d7b1c0c5b941e92eca5121/tt1568911
# http://api.themoviedb.org/2.1/Movie.getInfo/en/xml/963842d796d7b1c0c5b941e92eca5121/57212
# http://api.themoviedb.org/2.1/Movie.search/en/xml/963842d796d7b1c0c5b941e92eca5121/Rambo
# http://api.themoviedb.org/2.1/Movie.search/en/xml/963842d796d7b1c0c5b941e92eca5121/War Horse+2011
# http://api.themoviedb.org/2.1/Movie.getInfo/en/xml/963842d796d7b1c0c5b941e92eca5121/tt1568911
# {
# 
# "adult":false,
# 
# "backdrop_path":"/22DQWwjaam1LHTAEapxO2Wg7s2H.jpg",
# 
# "belongs_to_collection":{"id":1570,"name":"Die Hard Collection",
# "poster_path":"/yUzXU5DV3sfnqd2oc0tczXPtbe7.jpg",
# "backdrop_path":"/5kHVblr87FUScuab1PVSsK692IL.jpg"},
# 
# "budget":92000000,
# 
# "genres":[{"id":28,"name":"Action"},{"id":53,"name":"Thriller"}],
# 
# "homepage":"http://www.diehardmovie.com/",
# 
# "id":47964,
# 
# "imdb_id":"tt1606378",
# 
# "original_title":"A Good Day to Die Hard",
# 
# "overview":"Iconoclastic, take-no-prisoners cop John McClane, finds himself for the first time on foreign soil after traveling to Moscow to help his wayward son Jack - unaware that Jack is really a highly-trained CIA operative out to stop a nuclear weapons heist. With the Russian underworld in pursuit, and battling a countdown to war, the two McClanes discover that their opposing methods make them unstoppable heroes.",
# 
# "popularity":12.922934255187,
# 
# "poster_path":"/c2SQMd00CCGTiDxGXVqA2J9lmzF.jpg",
# 
# "production_companies":[{"name":"20th Century Fox","id":25}],
# 
# "production_countries":[{"iso_3166_1":"US","name":"United States of America"}],
# 
# "release_date":"2013-02-14",
# 
# "revenue":304654182,
# 
# "runtime":97,
# 
# "spoken_languages":[{"iso_639_1":"en","name":"English"},{"iso_639_1":"ru","name":"Pусский"}],
# 
# "status":"Released",
# 
# "tagline":"Yippee Ki-Yay Mother Russia",
# 
# "title":"A Good Day to Die Hard",
# 
# "vote_average":5.2,
# 
# "vote_count":2202}
}

sub ParseTMDb {
	my ($xml, $api, $title, $re, $tmdb_id, $tt, $user_agent, $edit) = @_ ;
	my ($vid_id, $vid_title, $aka, $rated, $vid_year, $released, $lang, $genre, $director, $writer, $actors, $run, $rate, $votes, $plot, $image_url, $links) = ('') x 17;
	my $count = 0;
	my $record = '';
	
	foreach (@$xml){
		chomp;
		# utf8 > &#nnn;
		s/([^\x20-\x7F])/'&#'.ord($1).';'/gse;
		
		if (m!^ +<movies>Nothing found.</movies>!){$record='No listing found at The Movie Database';}
		elsif (m!^ +<id>(\d+)</id>!){
			$vid_id = $1;
			$count ++;
		}
		#elsif (m!^ +<name>([^<]*)</name>!){$title="Title.....: $1<br>\t";}
		elsif (m!^ +<name>([^<]*)</name>!){
 			$vid_title = $1; # VS listing $title
# 			$vid_title =~ s!&#\d+;!!g;
# 			$vid_title =~ s!(\w)[.*#](\w)!$1 $2!g;
# 			$vid_title =~ s![:()"',\!.?*#-]!!g;
# 			$vid_title =~ s![=&]! !g;
		}
		elsif (m!^ +<alternative_name>([^<]*)</alternative_name>!){
 			$aka = $1;
# 			$aka =~ s!&#\d+;!!g;
# 			$aka =~ s!(\w)[.*#](\w)!$1 $2!g;
# 			$aka =~ s![:()"',\!.?*#-]!!g;
# 			$aka =~ s![=&]! !g;
		}
		elsif (m!^ +<certification>([^<]+)</certification>!){$rated="Rated.....: $1<br>\t";}
		elsif (m!^ +<released>([^<]*)</released>!){$released="Released..: $1<br>\t";}
		elsif (m!^ +<language_spoken.+ name="([^"]+)" native!){ $lang .= "$1, "; }
		elsif (m!^ +<category type="genre" name="([^"]+)"!){ $genre .= "$1, "; }
		elsif (m!^ +<person name="([^"]+?) ?".+job="Director".+url="[^\d]+/(\d+)" !){ $director .= ":$1:$2, "; }
		elsif (m!^ +<person name="([^"]+?) ?".+job="(?:Writer|Screenplay)".+url="[^\d]+/(\d+)" !){ $writer .= ":$1:$2, "; }
		elsif (m!^ +<person name="([^"]+?) ?".+job="Actor".+url="[^\d]+/(\d+)" !){ $actors .= ":$1:$2, "; }
		elsif (m!^ +<runtime>([^<]*)</runtime>!){$run="Runtime...: $1 min<br>\t";}
		elsif (m!^ +<rating>([^<]*)</rating>!){ unless ($rate){ $rate="Rating....: $1<br>\t"; } }
		elsif (m!^ +<votes>([^<]*)</votes>!){ unless ($votes){ $votes="Votes.....: $1<br>\t"; } }
		elsif (m!^ +<overview>([^<]*)</overview>!){
			$plot = $1;
			$plot =~ s!([^\n]{55,65} )!$1<br>            !g;
			$plot = "Plot......: $plot<br>";
		}
		elsif (m!^ +<imdb_id>(tt\d{7})</imdb_id>!){
			$tt = $1; 
			$links .= "<A HREF=\"http://www.imdb.com/title/$tt/\">IMDb</A>&nbsp;&nbsp;&nbsp;";
		}
		
		elsif (m!^ +<image type="poster" url="([^"]+)" size="w342"! and !$image_url){$image_url=$1;}
		elsif (m!^ +<url>([^<]+)</url>!){$links .= "<A HREF=\"$1\">TMDb</A>&nbsp;&nbsp;&nbsp;";}
		elsif (m!^ +<homepage>([^<]+)</homepage>!){$links .= "<A HREF=\"$1\">Movie site</A>&nbsp;&nbsp;&nbsp;";}
		elsif (m!^ +<trailer>([^<]+)</trailer>!){$links .= "<A HREF=\"$1\">Trailer</A>&nbsp;&nbsp;&nbsp;";}
		
		elsif (m!^ +</movie>!){
			if ($aka =~ m!$vid_title!i){ $aka = ''; }
# 			unless ($tmdb_id) { # why no unless ($tmdb_id){$tmdb_id = $1} above ###... option to use the alt title?
# 				$vid_title = "[<a href=\"$VAR{'DbCgi'}?do=tmdb&amp;tt=&amp;nt=$title&amp;id=$vid_id&amp;re=$re\">$vid_title</a>]";
# 				if ($aka){ $aka = "[<a href=\"$VAR{'DbCgi'}?do=tmdb&amp;tt=&amp;nt=$title&amp;id=$vid_id&amp;re=$re\">$aka</a>]"; }
# 			}
			$vid_title = "Title.....: $vid_title<br>\t";
			if ($aka){ $aka = "AKA.......: $aka<br>\t"; }
			if ($lang){ $lang =~ s!, $!!; $lang = "Language..: $lang<br>\t"; }
			if ($genre){ $genre =~ s!, $!!; $genre="Genre.....: $genre<br>\t"; }
			if ($director){ 
				$director =~ s!([^\n]{70,80},)!$1<br>           !g;
				#$director =~ s!:([^:]+):(\d+),!<A HREF="http://www.themoviedb.org/person/$2">$1</A>,!g;
				$director =~ s!, ?$!!; 
				$director =~ s!,<br>            $!!; 
				$director="Director..: $director<br>\t"; 
			}
			if ($writer){ 
				$writer =~ s!([^\n]{70,80},)!$1<br>           !g;
				#$writer =~ s!:([^:]+):(\d+),!<A HREF="http://www.themoviedb.org/person/$2">$1</A>,!g;
				$writer =~ s!, ?$!!; 
				$writer =~ s!,<br>            $!!; 
				$writer="Writer....: $writer<br>\t"; 
			}
			if ($actors){ 
				$actors =~ s!([^\n]{70,80},)!$1<br>           !g;
				#$actors =~ s!:([^:]+):(\d+),!<A HREF="http://www.themoviedb.org/person/$2">$1</A>,!g;
				$actors =~ s!, ?$!!;
				$actors =~ s!,<br>            $!!;
				$actors="Actors....: $actors<br>\t"; 
			}
			$links = "<br>Links.....: $links<br>\t";
			if ($user_agent and $tt){ # $user_agent and edit don't get passed with $tmdb_id lookup
				my ($r, $v) = &DCImdb($tt, $title, $user_agent, $edit);
				if ($r and $v){
					$rate = "Rating....: $r<br>\t";
					$votes = "Votes.....: $v<br>\t";
				}
			}
			$record .= "$vid_id$tt $title\t$vid_title$aka$lang$released$rated$genre$director$writer$actors$run$rate$votes$plot$links$DateTime[2]\n";
			($genre, $director, $writer, $actors, $links, $rate, $votes) = ('') x 7;
		}
	}
	return ($record, $count, $vid_id, $image_url, $tt);
}

sub DCImdb {
	my ($tt, $title, $user_agent, $edit) = @_;
	my $rated;
	my $votes;
	unless ($edit eq 'up'){
		open (RDB, "<$VAR{'DataDir'}/ppweb_dcimdb.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/ppweb_dcimdb.txt, $! (LI01)", 1, 0);
		while (<RDB>){
			if ($tt and m!^$tt [^\t]+\t([\d.]+) \((\d+)!){#\t$ratedate ($votesotes)
				$rated = $1;
				$votes = $2;
				&Print ("Got DC IMDb API rating/votes (cached): $rated/$votes (LI02)", 5, 0);
				last;
			}
		}
		close RDB or warn $!;
	}
	unless ($rated and $votes){
		my $response = $user_agent->get("http://deanclatworthy.com/imdb/?id=$tt&type=text");
		if ($response->is_success and $response->decoded_content) {
			#&Print ('DCimdb: '.$response->decoded_content.' (TM06)', 5, 0);
			my ($lang, $genre, $run) = ('') x 3;
			# rating|Ratings: 5.8/10 from 43,088 users
			if ($response->decoded_content =~ m!rating\|Ratings:\s([\d.]+)!){ $rated = $1; }
			if ($response->decoded_content =~ m!rating\|([\d.]+)\n!){ $rated = $1; }
			if ($response->decoded_content =~ m!votes\|(\d+)\n!){ $votes = $1; }
			if ($response->decoded_content =~ m!genres\|([^\n]+)\n!){ $genre = $1; }
			if ($response->decoded_content =~ m!languages\|([^\n]+)\n!){ $lang = $1; }
			if ($response->decoded_content =~ m!runtime\|(?:\w+:)?(\d+min)!){ $run = $1; }
			
			if ($response->decoded_content =~ m!Exceeded API usage limit!){
				&Print ('DC IMDb API usage limit (30 requests per hour) exceeded (TM20)', 1, 0);
			}
			
			if ($response->decoded_content =~ m!error\|Film not found$!){
				&Print ('Film (rating/votes) not found at DC IMDb API (TM20)', 4, 0);
			}
			elsif ($rated and $votes){
				&Print ("Got DC IMDb API rating/votes: $rated/$votes (LI02)", 4, 0);
				if ($edit eq 'up'){
					local ($^I, @ARGV) = ('.bak', "$VAR{'DataDir'}/ppweb_dcimdb.txt");
					while(<>){
						if ($. == 1) { 
							print "$tt $title\t$rated ($votes)  $genre  $run  $lang\n";
							unless (m!^$tt!){ print; } # replaced record on 1st line
						}
						elsif (m!^$tt!){ next; } # replaced record elsewhere
						else { print; }
					}
				}
				else {
					open (WDB, ">>$VAR{'DataDir'}/ppweb_dcimdb.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/ppweb_dcimdb.txt, $! (TM21)", 1, 0);
						print WDB "$tt $title\t$rated ($votes)  $genre  $run  $lang\n";
					close WDB or warn $!;
				}
				
			}
			else { &Print ('DC IMDb API returned no rating and/or votes, using TMDb data (TM22)', 4, 0); }
# 				&Print ('DC IMDb API reply had no rating and/or votes, writing response to: '.$VAR{'DataDir'}.'/dcimdb_response.txt (TM22)', 3, 0);
# 				open (WDB, ">$VAR{'DataDir'}/dcimdb_response.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/dcimdb_response.txt, $! (TM06)", 1, 0);
# 					print WDB $response->headers_as_string;
# 					print WDB $response->decoded_content;
# 				close WDB or warn $!;
# 			}
		}
		else { &Print ('DC IMDb API record fetch failed: '.$response->status_line.' (TM22)', 1, 0); }
	}
	return ($rated, $votes);
}

1;